package com.zbkj.client.controller;

import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.common.request.client.MaterialAddRequest;
import com.zbkj.common.request.client.BatchDeleteRequest;
import com.zbkj.client.service.MaterialService;
import com.zbkj.common.model.assets.Material;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.response.client.AssetCountResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.common.utils.FileDownloadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zbkj.common.request.client.CreateFolderRequest;
import com.zbkj.common.vo.client.CreateFolderVo;
import com.zbkj.client.service.KnowledgeService;
import com.zbkj.client.service.ClientProductService;
import com.zbkj.common.model.assets.Knowledge;
import com.zbkj.common.model.assets.ClientProduct;
import com.zbkj.common.exception.CrmebException;

@RestController
@RequestMapping("/api/client/assets")
@Api(tags = "素材管理")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    @Autowired
    private ClientTokenComponent clientTokenComponent;

    @Autowired
    private KnowledgeService knowledgeService;

    @Autowired
    private ClientProductService clientProductService;

    @PostMapping(value = "/addMaterial", consumes = "multipart/form-data")
    @ApiOperation(value = "添加素材")
    public CommonResult<Map<String, Object>> addMaterial(
                @RequestParam("name") String name,
                @RequestParam(value = "parentId", required = false) Integer parentId,
                @RequestParam("isFolder") Integer isFolder,
                @RequestParam(value = "duration",required = false) Integer duration,
                @RequestParam(value = "file", required = false) MultipartFile file,
                HttpServletRequest httpRequest) {
        // 组装请求对象
        MaterialAddRequest request = new MaterialAddRequest();
        request.setName(name);
        request.setParentId(parentId);
        request.setIsFolder(isFolder);
        request.setDuration(duration);
        request.setFile(file);

        String token = httpRequest.getHeader("token");
        Integer userId =clientTokenComponent.getLoginUser(httpRequest);

        // 新增：判断parentId对应的文件夹是否存在且未被删除，且归属当前用户，且必须是文件夹
        if (parentId != null && parentId != 0) {
            Material parent = materialService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权查看该文件夹");
            }
            if (parent.getIsFolder() == null || parent.getIsFolder() == 0) {
                return CommonResult.failed("请在文件夹下操作");
            }
        }

        ClientLoginResponse userInfo = clientTokenComponent.getUserInfo(userId, token);

        Integer merId = userInfo.getMerId();

        Material material = materialService.addMaterial(request, userId, merId);

        Map<String, Object> data = new HashMap<>();
        data.put("result", 1);

        return CommonResult.success(data);
    }

    @ApiOperation(value = "获取素材列表")
    @GetMapping("/listMaterial")
    public CommonResult<List<Material>> listMaterial(@RequestParam(value = "parentId", required = false) Integer parentId, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }

        if (parentId != null && parentId != 0) {
            Material parent = materialService.getById(parentId);
            if (parent == null || parent.getIsDel() == null || parent.getIsDel() != 0) {
                return CommonResult.failed("访问出错");
            }
            if (!userId.equals(parent.getUserId())) {
                return CommonResult.failed("无权查看该文件夹");
            }
        }
        List<Material> list = materialService.listMaterial(userId, parentId);
        return CommonResult.success(list);
    }

    @ApiOperation(value = "根据ID获取素材详情")
    @GetMapping("/getMaterial")
    public CommonResult<Material> getMaterial(@RequestParam("id") Integer id, HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        if (id == null) {
            return CommonResult.failed("素材ID不能为空");
        }
        
        Material material = materialService.getById(id);
        if (material == null) {
            return CommonResult.failed("素材不存在");
        }
        
        if (material.getIsDel() == null || material.getIsDel() != 0) {
            return CommonResult.failed("素材已被删除");
        }
        
        if (!userId.equals(material.getUserId())) {
            return CommonResult.failed("无权查看该素材");
        }
        
        return CommonResult.success(material);
    }


    @ApiOperation(value = "批量删除素材（软删除）")
    @PostMapping("/delMaterial")
    public CommonResult<Map<String, Object>> delMaterial(@RequestBody BatchDeleteRequest request, HttpServletRequest httpRequest) {
        List<Integer> ids = request.getIds();
        if (ids == null || ids.isEmpty()) {
            return CommonResult.failed("请选择要删除的素材");
        }
        
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        if (userId == null) {
            return CommonResult.failed("用户未登录");
        }
        
        // 校验所有id对应的记录
        for (Integer id : ids) {
            Material material = materialService.getById(id);
            if (material == null || material.getIsDel() == null || material.getIsDel() != 0) {
                return CommonResult.failed("素材ID " + id + " 不存在或已被删除");
            }
            if (!userId.equals(material.getUserId())) {
                return CommonResult.failed("无权操作素材ID " + id);
            }
        }
        
        boolean result = materialService.batchDelMaterial(ids);
        Map<String, Object> data = new HashMap<>();
        data.put("result", result ? 1 : 0);
        return CommonResult.success(data);
    }
} 